/**
 * sysRoleServiceImpl
 * 项目名称:分秒金融
 *
 * @author lunli
 *
 * 功能描述:角色管理
 * 
 * 历史版本:2017-03-28 v1.0.0 lunli  创建:
 * 
 */
package com.fmjr.sys.sysRole.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fmjr.common.base.exception.BusinessException;
import com.fmjr.common.base.util.Pager;
import com.fmjr.common.util.SqlUtil;
import com.fmjr.sys.sysPermission.bean.SysPermission;
import com.fmjr.sys.sysRole.bean.SysRole;
import com.fmjr.sys.sysRole.dao.SysRoleDao;
import com.fmjr.sys.sysRole.service.ISysRoleService;
import com.fmjr.sys.sysRolePermission.bean.SysRolePermission;
import com.fmjr.sys.sysRolePermission.dao.SysRolePermissionDao;
import com.fmjr.sys.sysUserRole.bean.SysUserRole;
import com.fmjr.sys.sysUserRole.dao.SysUserRoleDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service("sysRoleService")
public class  SysRoleServiceImpl implements ISysRoleService {
	
	private static  Logger logger = LoggerFactory.getLogger(SysRoleServiceImpl.class);

	@Autowired
    private SysRoleDao sysRoleDao;
	@Autowired
	private SysUserRoleDao sysUserRoleDao;
	
	@Autowired
	private SysRolePermissionDao rolePermissionDao;

	/**
	 * 根据条件查询角色记录
	 * @author lunli
	 * @param  pager
	 * @return SysRoleList
	 * @throws BusinessException
	 */
	public void selectSysRoleList(Pager<SysRole> pager) throws BusinessException{
		int totalCount = sysRoleDao.selectSysRoleCount(pager);
		int numPerPage = SqlUtil.checkPageSize(pager.getNumPerPage());
		int currentPage = SqlUtil.checkPageCurrent(totalCount, numPerPage, pager.getPageNum());
		pager.setLimitStart(SqlUtil.countOffset(currentPage, numPerPage));
		pager.setPageSize(numPerPage);
		pager.setCurrentPage(currentPage);
		pager.setTotalCount(totalCount);
		pager.setTotalPage(totalCount%numPerPage==0?totalCount/numPerPage:totalCount/numPerPage+1);
		List<SysRole> list = sysRoleDao.selectSysRoleList(pager);
		pager.setList(list);
	}
	
	/**
	 * 根据ID查询角色记录
	 * @author lunli
	 * @param id
	 * @return domain
	 * @throws BusinessException
	 */
	public SysRole selectSysRoleById(Long id) throws BusinessException{
		return sysRoleDao.selectSysRoleById(id);
	}

	/**
	 *  删除角色记录
	 * @author lunli	 
	 * @param id
	 * @throws BusinessException
	 */
	@Transactional(rollbackFor=BusinessException.class)
	public int deleteSysRoleById(Long id) throws BusinessException{
		return sysRoleDao.deleteSysRoleById(id);
	}
	
	/**
	 * 修改角色记录
	 * @author lunli
	 * @param sysRole
	 * @throws BusinessException
	 */
	@Transactional(rollbackFor=BusinessException.class)
	public int updateSysRole(SysRole sysRole) throws BusinessException{
		return sysRoleDao.updateSysRole(sysRole);
	}

	/**
	 * 新增角色记录
	 * @author lunli
	 * @param sysRole
	 * @return
	 * @throws BusinessException
	 */
	@Transactional(rollbackFor=BusinessException.class)
	public int createSysRole(SysRole sysRole) throws BusinessException{
		return sysRoleDao.createSysRole(sysRole);
	}

	@Override
	public List<SysRole> searchRoleByUserId(Long userId) {
		List<SysUserRole> listRolsId = sysUserRoleDao.searchRoleByUserId(userId);
		if(listRolsId.size() == 0 || listRolsId == null){
			return null;
		}
		List<Long> listIds = new LinkedList<Long>();
		for(int i = 0;i<listRolsId.size();i++){
			listIds.add(listRolsId.get(i).getSysRoleId());
		}
		return sysRoleDao.searchRoleByIds(listIds);
	}

	@Override
	public List<SysRole> getRoleAll() {
		return sysRoleDao.selectSysRoleAll();
	}

	@Override
	public int save_authorization(Long Roleid, SysPermission sysPermission) {
		
//		System.out.println("-----------"+Roleid+"=============="+sysPermission.getListPermission());
		
		List<SysRolePermission> rolePermissionList = rolePermissionDao.searchRolePermissionByRoleId(Roleid);
//		for(SysRolePermission li : rolePermissionList){
//			System.out.println("----------"+li.getId());
//		}
		
		if(sysPermission.getListPermission() != null && sysPermission.getListPermission().length() >0){ 
			String json = sysPermission.getListPermission().replaceAll("&quot;", "\"");
			List<SysPermission> list =  JSONObject.parseArray(json, SysPermission.class); //提交过来的
			List<Long> listPersionIds = new ArrayList<Long>();
			for(SysPermission li : list){
				listPersionIds.add(li.getId());
			}
			
			
			Map<Long,SysRolePermission> mapSysRolePermission = new HashMap<Long,SysRolePermission>();
			for(SysRolePermission l :rolePermissionList){ 
				mapSysRolePermission.put(l.getSysPermissionId(), l);
			}
			Set<Long> keySet = mapSysRolePermission.keySet();//数据库的角色资源Id
			
			SysRolePermission createRolePermission = null;
			for(Long li : listPersionIds){ //提交的
				if(mapSysRolePermission.get(li) == null){ //数据库
					createRolePermission = new SysRolePermission();
					createRolePermission.setSysRoleId(Roleid);
					createRolePermission.setSysPermissionId(li);
					rolePermissionDao.createSysRolePermission(createRolePermission);
				}
			}
			for(Long l : keySet){
				if(!listPersionIds.contains(l)){
					rolePermissionDao.deleteSysRolePermissionById(mapSysRolePermission.get(l).getId());
				}
			}
			return 1;
		}

		if(sysPermission.getListPermission() == null || sysPermission.getListPermission().length() == 0){
			logger.debug("角色ID"+Roleid+"取消所有相关资源");
			for(SysRolePermission li : rolePermissionList){
				rolePermissionDao.deleteSysRolePermissionById(li.getId());
				logger.debug("资源ID"+li.getId()+"已被删除"+",对应RoleId是"+Roleid);
			}
			return 1;
		}
		return -1;
	}

}
